<script setup>
import ip from '@/utils/baseURL.js';
import { ref, computed, onMounted, watch } from 'vue'
import axios from 'axios'

// 标签页状态和分页状态
const activeTab = ref('all')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 项目数据
const allProjects = ref([]) // 存储所有项目数据
const displayProjects = ref([]) // 当前显示的项目数据

// 添加年份筛选相关的状态
const selectedYear = ref(null)
const loading = ref(false)

// 获取所有可选年份
const yearOptions = computed(() => {
    const years = new Set(allProjects.value.map(project => project.startTime[0]))
    return Array.from(years).sort((a, b) => b - a) // 年份从大到小排序
})

// 处理年份清除
const handleYearClear = () => {
    selectedYear.value = null
    applyFilters()
}

// 从后端获取项目数据
const fetchProjects = async () => {
  loading.value = true
  try {
    const response = await axios.get(ip + '/inter/project/getOurProjects')
    if (response.data.code === 200) {
      allProjects.value = response.data.data.records.map(project => ({
        id: project.projectId,
        title: project.projectName,
        leader: project.mainPeople,
        members: project.member || '暂无成员',
        startTime: project.startTime, // 保存完整的开始时间数组
        timeRange: `${project.startTime.join('.')} - ${project.endTime.join('.')}`,
        status: project.status === 0 ? '在研' : project.status === 1 ? '已结题' : '已获奖',
        description: project.briInfo,
        fruits: project.fruits || '暂无成果'
      }))
      // 按开始时间排序
      .sort((a, b) => {
        // 比较年份
        if (b.startTime[0] !== a.startTime[0]) {
          return b.startTime[0] - a.startTime[0]
        }
        // 如果年份相同，比较月份
        if (b.startTime[1] !== a.startTime[1]) {
          return b.startTime[1] - a.startTime[1]
        }
        // 如果月份相同，比较日期
        return b.startTime[2] - a.startTime[2]
      })
      
      applyFilters() // 应用筛选并更新分页
    }
  } catch (error) {
    console.error('获取项目数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 应用筛选并更新分页
const applyFilters = () => {
    let filtered = [...allProjects.value]

    // 按年份筛选
    if (selectedYear.value) {
        filtered = filtered.filter(project => 
            project.startTime[0] === selectedYear.value
        )
    }

    // 按状态筛选
    if (activeTab.value !== 'all') {
        filtered = filtered.filter(project => {
            switch (activeTab.value) {
                case 'ongoing':
                    return project.status === '在研'
                case 'completed':
                    return project.status === '已结题'
                case 'awarded':
                    return project.status === '已获奖'
                default:
                    return true
            }
        })
    }

    // 更新总数
    total.value = filtered.length
    
    // 应用分页
    const startIndex = (currentPage.value - 1) * pageSize.value
    const endIndex = startIndex + pageSize.value
    displayProjects.value = filtered.slice(startIndex, endIndex)
    
    // 如果当前页没有数据且不是第一页，则返回第一页
    if (displayProjects.value.length === 0 && currentPage.value > 1) {
        currentPage.value = 1
        applyFilters() // 重新应用筛选
    }
}

// 监听筛选条件变化
watch([selectedYear, activeTab, currentPage, pageSize], () => {
    applyFilters()
})

// 标签切换处理
const handleTabClick = () => {
    currentPage.value = 1
    selectedYear.value = null  // 切换标签时重置年份筛选
    applyFilters()
}

// 年份变化处理
const handleYearChange = () => {
    currentPage.value = 1
    applyFilters()
}

// 分页处理
const handleSizeChange = (val) => {
    pageSize.value = val
    currentPage.value = 1
    applyFilters()
}

const handleCurrentChange = (val) => {
    currentPage.value = val
    applyFilters()
}

// 页面加载时获取数据
onMounted(() => {
    fetchProjects()
})
</script>
<template>
    <div class="projects-container">
        <div class="main-content">
            <!-- 页面标题 -->
            <div class="page-header">
                <h1>科研项目</h1>
            </div>

            <!-- 项目分类标签和年份筛选 -->
            <div class="filter-section">
                <div class="project-tabs">
                    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
                        <el-tab-pane label="全部项目" name="all"></el-tab-pane>
                        <el-tab-pane label="在研项目" name="ongoing"></el-tab-pane>
                        <el-tab-pane label="已结题项目" name="completed"></el-tab-pane>
                        <el-tab-pane label="已获奖项目" name="awarded"></el-tab-pane>
                    </el-tabs>
                </div>
                <div class="year-filter">
                    <el-select v-model="selectedYear" placeholder="选择年份" clearable @clear="handleYearClear" @change="handleYearChange">
                        <el-option
                            v-for="year in yearOptions"
                            :key="year"
                            :label="`${year}年`"
                            :value="year"
                        />
                    </el-select>
                </div>
            </div>

            <!-- 项目列表 -->
            <div class="project-list" v-loading="loading">
                <el-card v-for="project in displayProjects" :key="project.id" class="project-item">
                    <div class="project-content">
                        <h2 class="project-title">
                            <span class="title-text">{{ project.title }}</span>
                            <el-tag 
                                :type="project.status === '在研' ? 'danger' : 
                                      project.status === '已结题' ? 'success' : 
                                      'warning'" 
                                size="small"
                            >
                                {{ project.status }}
                            </el-tag>
                        </h2>
                    
                        <div class="project-info">
                            <div class="info-item">
                                <span class="label">负责人：</span>
                                <span class="value">{{ project.leader }}</span>
                            </div>
                            <div class="info-item">
                                <span class="label">项目成员：</span>
                                <span class="value">{{ project.members }}</span>
                            </div>
                            <div class="info-item">
                                <span class="label">起止时间：</span>
                                <span class="value">{{ project.timeRange }}</span>
                            </div>
                            <div class="info-item">
                                <span class="label">项目成果：</span>
                                <span class="value">{{ project.fruits }}</span>
                            </div>
                        </div>
                        <div class="project-description">
                            <div class="description-title">项目简介：</div>
                            <p>{{ project.description }}</p>
                        </div>
                    </div>
                </el-card>

                <!-- 分页器 -->
                <div class="pagination-container">
                    <el-pagination
                        v-model:current-page="currentPage"
                        v-model:page-size="pageSize"
                        :total="total"
                        :page-sizes="[10, 20, 30, 50]"
                        layout="total, sizes, prev, pager, next, jumper"
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                    />
                </div>
            </div>
        </div>
    </div>
</template>



<style lang="scss" scoped>
.projects-container {
    .main-content {
        max-width: 1400px;
        margin: 0 auto;
        padding: 40px 20px;
    }

    .page-header {
        margin-bottom: 40px;
        text-align: center;

        h1 {
            font-size: 36px;
            color: #333;
            margin: 0;
            position: relative;
            display: inline-block;
            padding-bottom: 15px;

            &::after {
                content: '';
                position: absolute;
                bottom: 0;
                left: 50%;
                transform: translateX(-50%);
                width: 60px;
                height: 4px;
                background-color: #86B943;
            }
        }
    }

    .filter-section {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 30px;
        
        .project-tabs {
            flex: 1;
            margin-bottom: 0;
        }

        .year-filter {
            width: 180px;
            margin-bottom: 0;
        }
    }

    .project-list {
        .project-item {
            margin-bottom: 20px;

            .project-content {
                .project-title {
                    font-size: 24px;
                    color: #333;
                    margin: 0 0 15px 0;
                    display: flex;
                    align-items: center;
                    gap: 10px;

                    .title-text {
                        font-weight: 600;
                    }
                }

                .project-info {
                    display: grid;
                    grid-template-columns: repeat(2, 1fr);
                    gap: 15px;
                    margin-bottom: 20px;

                    .info-item {
                        .label {
                            color: #666;
                            margin-right: 5px;
                        }

                        .value {
                            color: #333;
                            font-weight: 500;
                        }
                    }
                }

                .project-description {
                    .description-title {
                        color: #666;
                        margin-bottom: 10px;
                    }

                    p {
                        color: #666;
                        line-height: 1.6;
                        margin: 0;
                    }
                }
            }
        }
    }

    .pagination-container {
        margin-top: 30px;
        display: flex;
        justify-content: center;
    }
}

// 响应式布局
@media (max-width: 768px) {
    .project-info {
        grid-template-columns: 1fr !important;
    }

    .page-header {
        h1 {
            font-size: 28px !important;
        }
    }
}
</style>